/**
 * 预览图片
 */
import './index.less'
class previewImage {
    /**
     * 
     * @param {String} url 首张图片 
     * @param {Array} list 切换的列表url
     */
    constructor(url, { list }) {
        this.url = url;
        this.list = list || [];
        this.init();
    }

    init() {
        let element = document.createElement('div');
        element.id = 'q-previewImage';
        element.className = 'q-previewImage-box';
        element.innerHTML = this.getHTML();
        this.element = element;
        // 异步获取   
        Promise.resolve().then(() => {
            let close = document.getElementById('q-previewImage-close');
            let previewImage = document.getElementById(this.element.id);
            let img = document.getElementById('q-img-box-img');
            let suoxiao = document.getElementById('q-tools-suoxiao');
            let fangda = document.getElementById('q-tools-fangda');
            let quanping = document.getElementById('q-tools-quanping');
            let zuoxuanzhuan = document.getElementById('q-tools-zuoxuanzhuan');
            let youxuanzhuan = document.getElementById('q-tools-youxuanzhuan');
            let slideImageLeft = document.getElementById('q-slideImage-left');
            let slideImagRight = document.getElementById('q-slideImage-right');
            close.onclick = () => { this.close(img); }
            suoxiao.onclick = () => { this.suoxiao(img); }
            quanping.onclick = () => { this.reset(img); }
            fangda.onclick = () => { this.fangda(img); }
            zuoxuanzhuan.onclick = () => { this.zuoxuanzhuan(img); }
            youxuanzhuan.onclick = () => { this.youxuanzhuan(img); }
            slideImageLeft.onclick = () => { this.slideImage(img, 'left'); }
            slideImagRight.onclick = () => { this.slideImage(img, 'right'); }
            previewImage.addEventListener('wheel', (e) => { this.scaleImage(e, img) })
            this.isMove = false;
            this.flag = true;
            img.addEventListener('mousedown', (e) => {
                this.isMove = true;
                this.startX = e.clientX || 0;
                this.startY = e.clientY || 0;
                let transform = getComputedStyle(img)['transform'];
                let val = transform.replaceAll('(', '').replaceAll(")", "").split(',').slice(4, 6)
                this.x = Number(val[0]) || 0;
                this.y = Number(val[1]) || 0;
            })
            img.addEventListener('touchstart', (e) => {
                e.clientX = e.touches[0].clientX;
                e.clientY = e.touches[0].clientY;
                this.isMove = true;
                this.startX = e.clientX || 0;
                this.startY = e.clientY || 0;
                let transform = getComputedStyle(img)['transform'];
                let val = transform.replaceAll('(', '').replaceAll(")", "").split(',').slice(4, 6)
                this.x = Number(val[0]) || 0;
                this.y = Number(val[1]) || 0;
            })
            // 节流
            img.addEventListener('mousemove', (e) => {
                if (!this.isMove) return
                if (!this.flag) return
                this.flag = false;
                this.mousemoveTimeBar = setTimeout(() => {
                    this.flag = true;
                    this.moveImage(e, img)
                }, 10);
            })
            img.addEventListener('touchmove', (e) => {
                e.clientX = e.touches[0].clientX;
                e.clientY = e.touches[0].clientY;
                if (!this.isMove) return
                if (!this.flag) return
                this.flag = false;
                this.mousemoveTimeBar = setTimeout(() => {
                    this.flag = true;
                    this.moveImage(e, img);
                }, 10);
            })
            // img.addEventListener('mouseup', (e) => {
            //     this.mouseUp();
            // })
            // 监听窗口鼠标弹起
            window.addEventListener('mouseup', () => {
                this.mouseUp();
            })
            img.addEventListener('touchend', () => {
                this.mouseUp();
            })
        })
        this.append(this.element)
    }

    // 切换图片
    slideImage(img, type) {
        this.reset(img);
        this.idx =this.idx ||  0;
        let len = this.list.length;
        if(len==0) return;
        this.list.some((item, index) => {
            if (item == this.url) {
                this.idx = index;
                return true
            }
        })
        if (type == 'left') {
            this.idx--;
            if (this.idx < 0) {
                this.idx = len - 1;
            }
         
        } else {
            this.idx++;
            if (this.idx > len - 1) {
                this.idx = 0
            }
        }
        img.src = this.list[this.idx];
        this.url = this.list[this.idx];
    }

    // 更新图片
    updateImageTransform(img) {
        // console.log(img)
        // console.log(`translate(${this.resultX || 0}px,${this.resultY || 0}px) scale(${this.scaleVal || 1}) rotateZ(${this.rotateZ || 0}deg)`)
        img.style.transform = `translate(${this.resultX || 0}px,${this.resultY || 0}px) scale(${this.scaleVal || 1}) rotateZ(${this.rotateZ || 0}deg)`;
        console.log(img.style.transform, '===')
    }

    // 左旋转
    zuoxuanzhuan(img) {
        this.rotateZ = this.rotateZ || 0;
        this.rotateZ = this.rotateZ - 90;
        if (this.rotateZ <= -360) {
            this.rotateZ = 0;
        }
        console.log(this.rotateZ)
        this.updateImageTransform(img);
    }

    // 右旋转
    youxuanzhuan(img) {
        this.rotateZ = this.rotateZ || 0;
        this.rotateZ = this.rotateZ + 90;
        if (this.rotateZ >= 360) {
            this.rotateZ = 0;
        }
        console.log(this.rotateZ)
        this.updateImageTransform(img);
    }

    // 图片缩小
    suoxiao(img) {
        this.scaleVal = this.scaleVal || 1;
        this.scaleVal = this.scaleVal - 0.05;
        if (this.scaleVal <= 0.2) {
            this.scaleVal = 0.2
        }
        this.getResultXY(img);
        this.updateImageTransform(img);
    }

    // 图片放大
    fangda(img) {
        this.scaleVal = this.scaleVal || 1;
        this.scaleVal = this.scaleVal + 0.05;
        if (this.scaleVal >= 3) {
            this.scaleVal = 3;
        }
        this.getResultXY(img);
        this.updateImageTransform(img);
    }

    // 获取x、y的位置
    getResultXY(img) {
        if (!this.resultX && !this.resultY) {
            let transform = getComputedStyle(img)['transform'];
            let val = transform.replaceAll('(', '').replaceAll(")", "").split(',').slice(4, 6)
            this.resultX = Number(val[0]) || 0;
            this.resultY = Number(val[1]) || 0;
        }
    }

    // 缩放图片
    scaleImage(e, img) {
        this.scaleVal = this.scaleVal || 1;
        if (e.wheelDeltaY < 0) {
            // 缩小
            this.suoxiao(img);
        } else {
            // 放大
            this.fangda(img)
        }
        // console.log('=============scaleImage',this.resultX,this.resultY)

    }

    // 移动图片
    moveImage(e, img) {
        this.endX = e.clientX || 0;
        this.endY = e.clientY || 0;
        let x = (this.x || 0) + (this.endX - this.startX);
        let y = (this.y || 0) + (this.endY - this.startY);
        this.resultX = x;
        this.resultY = y;
        // console.log('=============moveImage',this.resultX,this.resultY)
        this.updateImageTransform(img);
    }
    // 鼠标弹起
    mouseUp() {
        this.isMove = false;
        this.startX = undefined;
        this.startY = undefined;
        this.endX = undefined;
        this.endY = undefined;
        if (this.mousemoveTimeBar) {
            // 清除节流定时器
            clearTimeout(this.mousemoveTimeBar);
            // 打开开关
            this.flag = true;
        }
    }
    // 重置大小
    reset(img) {
        this.resultX = 0;
        this.resultY = 0;
        this.scaleVal = 1;
        this.rotateZ = 0;
        this.updateImageTransform(img);
    }
    // 获取HTML
    getHTML() {
        /**
         * ondragstart="return false" 禁止图片拖动
         */
        const html = `
            <div class='img-box'>
                <img src=${this.url} class="img" id="q-img-box-img" ondragstart="return false" />
                <div id="q-previewImage-close" class='close'> 
                        <i class="iconfont icon-guanbi"></i>
                </div>

                <div class="tools">
                    <span id="q-tools-suoxiao">
                        <i class="iconfont icon-suoxiao"></i>
                    </span>
                    <span id="q-tools-fangda">
                        <i class="iconfont icon-fangda"></i>
                    </span>
                    <span id="q-tools-quanping">
                        <i class="iconfont icon-quanping"></i>
                    </span>
                    <span id="q-tools-zuoxuanzhuan">
                        <i class="iconfont icon-zuoxuanzhuan"></i>
                    </span>
                    <span id="q-tools-youxuanzhuan">
                        <i class="iconfont icon-youxuanzhuan"></i>
                    </span>
                </div>
              
                <span id="q-slideImage-left" style="display:${this.list.length>0?'inline':'none'}">
                    <i class="iconfont icon-zuojiantou_c"></i>
                </span>
                <span id="q-slideImage-right" style="display:${this.list.length>0?'inline':'none'}">
                    <i class="iconfont icon-youjiantou_c"></i>
                </span>
            </div>
        `
        return html
    }
    close(el) {
        if (el) {
            el.style.transform = '';
        }
        this.remove();
        this._HtmlVisibleScroll();
    }

    append(el) {
        this._HtmlHiddenScroll();
        document.body.appendChild(el);
    }

    remove() {
        document.body.removeChild(this.element);
    }

    // 显示滚动条
    _HtmlVisibleScroll() {
        let html = document.getElementsByTagName('html')[0];
        let body = document.body;
        html.style.overflow = "visible";
        body.style.overflow = "visible";
    }
    // 隐藏滚动条
    _HtmlHiddenScroll() {
        let html = document.getElementsByTagName('html')[0];
        let body = document.body;
        html.style.overflow = "hidden";
        body.style.overflow = "hidden";
    }
}

export default previewImage